package com.railway.common.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

/**
 * EasyUI框架与JSon相关的操作
 * 
 * @author wuyb
 * 
 */
public class EasyUIJsonUtil {
	

	/**
	 * 根据已整理好的数据map创建对应的JSon数据对象
	 * 
	 * @return
	 */
	private static String createJsonData(Map root,
			Map<Object, TreeSet<Map>> treedataMap) {

		if (root == null)
			return null;
		Object id =  root.get("id");
		if(id == null)throw new IllegalArgumentException("map item shoud include id key's value");
		TreeSet<Map> children = treedataMap.get(id);
		if (children != null) {
			List cList = new ArrayList();
			for (Map item : children) {
				String childJsonStr = createJsonData(item, treedataMap);
				cList.add(childJsonStr);
			}
			root.put("children", cList);
		}
		return Json.toJson(root);
	}
	
	/**
	 * 把List中的数据组织成以父ID为关键字，内容存放该Id的子对象列表的Map。
	 * @param treedataList
	 * @return
	 */
    public static Map<Object,TreeSet<Map>> createStructTreeData(List<Map> treedataList){
    	
		Map<Object, TreeSet<Map>> dataMap = new HashMap<Object, TreeSet<Map>>();
		for (Map<String, Object> treeItem : treedataList) {
			Object pId =  treeItem.get("parentId");
			if (pId == null)
				throw new IllegalArgumentException(
						"map item shoud include parentId key's value");
			TreeSet<Map> children = dataMap.get(pId);
			if (children == null) {// 列表未创建，则先创建，再把子对象放入。
				// 采用TreeSet是为了根据Order排序
				children = new TreeSet<Map>(new Comparator<Map>() {
					public int compare(Map o1, Map o2) {
						Integer n1 = (Integer) o1.get("order");
						Integer n2 = (Integer) o2.get("order");
						if (n1 == null || n2 == null)
							throw new IllegalArgumentException(
									"map item shoud include order key's value");
						if(n1.compareTo(n2)>=0)
							return 1;
						else return -1;
					}
				});
				children.add(treeItem);
				dataMap.put(pId, children);
			} else
				// 已存在，直接放入
				children.add(treeItem);
		}
		return dataMap;
    }
	/**
	 * 根据传入的数据创建Json数据流
	 * Map中的值应该包含"id”，"parentId"，"order"三个key
	 * @param root
	 * @param treedataList
	 * @return
	 */
	public static String createTreeJsonString(Map root, List<Map> treedataList) {
		Map<Object, TreeSet<Map>> dataMap = createStructTreeData(treedataList);
		String jsondataMap = createJsonData(root, dataMap );
		List jsonList = new ArrayList();
		jsonList.add(jsondataMap);
		return Json.toJson(jsonList);
	}

}
